package com.loan.system.service.impl;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.loan.common.utils.StringUtils;
import com.loan.system.create.domain.AssistPdfSearchBase;
import com.loan.system.create.service.IAssistPdfSearchBaseService;
import com.loan.system.domain.AssistFile;
import com.loan.system.domain.AssistType;
import com.loan.system.domain.pdf.DealRecord;
import com.loan.system.domain.pdf.PdfForm;
import com.loan.system.domain.pdf.PdfFormData;
import com.loan.system.domain.pdf.ResultDomain;
import com.loan.system.service.IAssistFileService;
import com.loan.system.service.IAssistTypeService;
import com.loan.system.service.IDealPdfServiceTemp;
import com.loan.system.utils.ReplacePdf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @PACKAGE_NAME: com.loan.system.service.impl
 * @CLASSNAME: IDealPdfServiceImpl
 * @DEACRIPTION:
 * @AUTHOR: GuoChen
 * @DATE: 2024/2/1
 * @WEEK: 周四
 **/
@Slf4j
@Service
public class IDealPdfServiceImplTemp implements IDealPdfServiceTemp {

    @Autowired
    private ReplacePdf replacePdf;
    @Autowired
    private IAssistFileService assistFileService;
    @Autowired
    private IAssistTypeService assistTypeService;
    @Autowired
    private IAssistPdfSearchBaseService assistPdfSearchBaseService;

    /**
     * 获取要处理的文件原始数据和需要处理的数组大小
     *
     * @param assistFile 文件信息
     */
    public ResultDomain getOriginalInfoAndDealSize(AssistFile assistFile) {
        log.info("解析PDF文件...");
        AssistType assistType = assistTypeService.selectAssistTypeById(assistFile.getAssistTypeId());
        ResultDomain resultDomain = new ResultDomain();
        resultDomain.setAssistFile(assistFile);
        resultDomain.setAssistType(assistType);
        String filePath = assistFile.getOriginalFilePath();
        try {
            Map<Integer, List<PdfForm>> pageMap = replacePdf.tranPdfToDomain(filePath);
            // 处理PDF金额数据
            log.info("处理收入数据！");
            this.getPdfTextMap(pageMap, true, resultDomain);
            log.info("处理支出数据！");
            this.getPdfTextMap(pageMap, false, resultDomain);
            log.info("数据处理完成!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("解析PDF文件出现异常：{}", e.getMessage());
        }
        return resultDomain;
    }

    /**
     * 随机生成指定总额的数额，并做映射
     *
     * @param resultDomain
     * @return
     */
    public ResultDomain createRomValueMapping(ResultDomain resultDomain) {
        log.info("随机生成随机数...");
        Map<Integer, List<PdfFormData>> inNeedDealMap = resultDomain.getInNeedDealMap();
        Map<Integer, List<PdfFormData>> outNeedDealMap = resultDomain.getOutNeedDealMap();
        if (resultDomain.getDesireInMoney() != null) {
            List<Integer> inMoneyList = getRandomValue("收入", resultDomain.getExcludeInMoney().intValue(), resultDomain.getDesireInMoney(), resultDomain.getDealInTotalSize());
            List<DealRecord> inDealRecords = mappingNameAndValue(resultDomain.getDesireInMoney(), inMoneyList, inNeedDealMap);
            resultDomain.setInDealRecord(inDealRecords);
            Integer dealTotalMoney = inMoneyList.stream().reduce(0, Integer::sum);
            resultDomain.setDealInTotalMoney(dealTotalMoney + resultDomain.getExcludeInMoney());
        }
        if (resultDomain.getDesireOutMoney() != null) {
            List<Integer> outMoneyList = getRandomValue("支出", resultDomain.getExcludeOutMoney().intValue(), resultDomain.getDesireOutMoney(), resultDomain.getDealOutTotalSize());
            List<DealRecord> outDealRecords = mappingNameAndValue(resultDomain.getDesireOutMoney(), outMoneyList, outNeedDealMap);
            resultDomain.setOutDealRecord(outDealRecords);
            Integer dealTotalMoney = outMoneyList.stream().reduce(0, Integer::sum);
            resultDomain.setDealOutTotalMoney(dealTotalMoney + resultDomain.getExcludeOutMoney());
        }
        return resultDomain;
    }

    /**
     * 生成PDF新文件
     *
     * @param resultDomain
     * @return
     */
    public AssistFile dealPdfTextAndCreateFile(ResultDomain resultDomain) {
        log.info("处理收数据...");
        this.replaceText(resultDomain.getInNeedDealMap(), resultDomain.getInDealRecord());
        log.info("处理支数据...");
        this.replaceText(resultDomain.getOutNeedDealMap(), resultDomain.getOutDealRecord());

        log.info("根据处理后的数据，创建新文件...");
        AssistFile assistFile = resultDomain.getAssistFile();
        String filePath = assistFile.getOriginalFilePath();
        String targetFilePath = assistFile.getNewFilePath();
        String fontPath = "E:\\tempDir\\font\\WeChat-Sans-Std-Regular.ttf";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        FileInputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //源文件pdf
            File file = new File(filePath);
            //目标文件
            File destFile = new File(targetFilePath);

            inputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(destFile);
            byte[] bytes = new byte[inputStream.available()];
            // 处理PDF金额数据
            log.info("处理收入数据！");
            Map<Integer, List<PdfFormData>> dealInMap = resultDomain.getInNeedDealMap();
            log.info("处理支出数据！");
            Map<Integer, List<PdfFormData>> dealOutMap = resultDomain.getOutNeedDealMap();

            inputStream.read(bytes);
            PdfReader reader = new PdfReader(bytes);
            //获取pdf页数
            int pageSize = reader.getNumberOfPages();
            log.info("bytes页数：{}", pageSize);
            this.dealPdfFileBytes(bytes, outputStream, dealInMap, dealOutMap, resultDomain);
            log.info("数据替换完成...");
            //得到替换后的文件字节
            byte[] byteArray = outputStream.toByteArray();
            //输出
            fileOutputStream.write(byteArray);
            assistFile.setNewFileUrl("download:" + assistFile.getNewFilePath());
            assistFileService.updateAssistFile(assistFile);
        } catch (Exception e) {
            log.error("处理PDF文件出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (fileOutputStream != null) fileOutputStream.close();
                if (inputStream != null) inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                log.error("关闭输入输出流异常：{}", e.getMessage());
                log.error(e.getMessage(), e);
            }
            log.info("文件创建成功：{}", assistFile.getNewFilePath());
        }
        return assistFile;
    }

    /**
     * 映射处理
     *
     * @param desireMoney 期待总额
     * @param moneyList   生成的总额数据
     * @param needDealMap 要做映射的数据
     * @return
     */
    private List<DealRecord> mappingNameAndValue(Integer desireMoney, List<Integer> moneyList, Map<Integer, List<PdfFormData>> needDealMap) {
        List<DealRecord> dealRecordList = new ArrayList<>();
        if (desireMoney != null) {
            if (needDealMap != null && needDealMap.size() > 0) {
                for (Integer pageNum : needDealMap.keySet()) {
                    List<PdfFormData> list = needDealMap.get(pageNum);
                    if (list != null && list.size() > 0) {
                        for (PdfFormData pdfFormData : list) {
                            DealRecord dealRecord = new DealRecord();
                            dealRecord.setName(pdfFormData.getName());
                            dealRecord.setWay(pdfFormData.getWay());
                            dealRecord.setType(pdfFormData.getType());
                            dealRecord.setMoney(pdfFormData.getMoney());
                            dealRecordList.add(dealRecord);
                        }
                    }
                }
                log.info("数据一一对应...");
                if (dealRecordList != null && dealRecordList.size() > 0 && moneyList != null && dealRecordList.size() == moneyList.size()) {
                    for (int i = 0; i < dealRecordList.size(); i++) {
                        dealRecordList.get(i).setDealMoney(moneyList.get(i));
                    }
                }
            }
        }
        return dealRecordList;
    }

    private void getPdfTextMap(Map<Integer, List<PdfForm>> map,
                               Boolean isInDeal,
                               ResultDomain result) {
        List<String> searchAllList = assistPdfSearchBaseService.selectAllList();
        List<AssistPdfSearchBase> searchBaseList = new ArrayList<>();
        AssistType assistType = result.getAssistType();
        String dealFlagName = assistType.getDealFlagName();
        String[] dealFlagNames = dealFlagName.split(",");
        String inOrOut = dealFlagNames[0]; // 收入
        if (!isInDeal) {
            inOrOut = dealFlagNames[1]; // 支出
        }
        log.info("处理{}金额数据...", inOrOut);
        BigDecimal excludeMoney = new BigDecimal(0); // 过滤不计算的金额
        BigDecimal originalTotalMoney = new BigDecimal(0); // 原始金额
        Map<Integer, List<PdfFormData>> dealMap = new LinkedHashMap<>();
        Integer totalSize = 0;
        if (!map.isEmpty()) {
            String filterTextColumn = assistType.getFilterTextColumn();
            Integer moneyColumn = Integer.parseInt(assistType.getDealTextColumn()); // 处理文本所在列
            // 过滤红包, 银行, 农信, 拼多多等关键字的收入信息
            // String excludeStr = "红包,银行,农信,拼多多,出行,亲属卡,充值,胡辣汤,返现,提现,早餐,水务,国网,电力,生活缴费,国家,拼车,烧饼,药店,炸鸡,牛肉汤,羊肉汤,代价,高速公路联网监控收费,特来电,洗衣,洗浴,悦来悦喜,丰巢,蜜雪冰城,充值,停车,馄饨,充电,火锅,面筋,小吃,副食,理发,沙龙,诊所,砂锅,美甲,蛋糕,宠物,面,水饺,拼车,CoCo,饮品,彩票,图文,土豆粉,代价,打车,餐馆,烧烤,肉夹馍,粥,茶,肯德基,麦当劳,快电,串串,加油站,石油,石化,邮政,中国,中科,内衣,餐馆,正新鸡排,便利,天然气,电网,水务,商户消费,快手,沪上阿姨,速运,馍店,送水,麻辣烫,瓜子,地铁,携程,去哪儿,铁路,客车运输,酸辣,火烧,米线";
            String excludeStr = assistType.getFilterTextContent();
            String[] filterColumns = filterTextColumn.split(",");
            Integer nameColumn = Integer.parseInt(filterColumns[0]); // 交易方名称所在列
            Integer wayColumn = Integer.parseInt(filterColumns[1]); // 交易方式所在列
            Integer typeColumn = Integer.parseInt(filterColumns[2]); // 交易类型所在列
            for (Integer pageNum : map.keySet()) {
                List<PdfFormData> dealList = new ArrayList<>();
                List<PdfForm> formList = map.get(pageNum);
                if (formList != null && formList.size() > 0) {
                    PdfForm form = formList.get(0);
                    if (form != null) {
                        List<List<PdfFormData>> dataBox = form.getData();
                        if (dataBox != null && dataBox.size() > 0) {
                            for (List<PdfFormData> box : dataBox) {
                                if (box != null && box.size() > 0) {
                                    for (int i = 0; i < box.size(); i++) {
                                        PdfFormData moneyData = box.get(moneyColumn);
                                        PdfFormData data = box.get(assistType.getDealFlagColumn());
                                        String text = data.getText();

                                        String name = box.get(nameColumn).getText().replaceAll("[\n\r\t]", ""); // 交易方名称
                                        String way = box.get(wayColumn).getText().replaceAll("[\n\r\t]", ""); // 交易方式(零钱/扫二维码)
                                        String type = box.get(typeColumn).getText().replaceAll("[\n\r\t]", ""); // 交易类型(收入/支出)
                                        String flag = String.join(",", name, way, type);

                                        if (StringUtils.equals(text, inOrOut)) {
                                            if (StringUtils.containsAny(flag, excludeStr.split(","))) {
                                                excludeMoney = excludeMoney.add(new BigDecimal(box.get(moneyColumn).getText()));
                                                break;
                                            }
                                            // 将数据添加到检索库中
                                            if (!searchAllList.contains(name) && StringUtils.isNotBlank(name)) {
                                                for (int j = 0; j < 2; j++) {
                                                    AssistPdfSearchBase assistPdfSearchBase = new AssistPdfSearchBase();
                                                    assistPdfSearchBase.setSearchBaseName(name);
                                                    assistPdfSearchBase.setSearchBaseNameType(j == 0 ? "0" : "1"); // 0交易方名称;1交易方式
                                                    assistPdfSearchBase.setSearchBaseType(isInDeal ? "0" : "1"); // 0收入;1支出
                                                    assistPdfSearchBase.setRemark("数据检索入库!");
                                                    searchBaseList.add(assistPdfSearchBase);
                                                }
                                            }
                                            originalTotalMoney = originalTotalMoney.add(new BigDecimal(box.get(moneyColumn).getText()));
                                            moneyData.setName(name);
                                            moneyData.setWay(way);
                                            moneyData.setType(type);
                                            moneyData.setMoney(box.get(moneyColumn).getText());
                                            // 为收入类型，则进行存储
                                            dealList.add(moneyData);
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (!dealList.isEmpty()) {
                    totalSize += dealList.size();
                    dealMap.put(pageNum, dealList);
                }
            }
        }
        originalTotalMoney = originalTotalMoney.add(excludeMoney);
        log.info("计算的原始{}总金额为：{}", inOrOut, originalTotalMoney.toString());
        log.info("需要处理的金额笔数为：{}", totalSize);
        if (isInDeal) {
            result.setInNeedDealMap(dealMap);
            result.setDealInTotalSize(totalSize);
            result.setOriginalInTotalMoney(originalTotalMoney.floatValue());
            result.setExcludeInMoney(excludeMoney.floatValue());
        } else {
            result.setOutNeedDealMap(dealMap);
            result.setDealOutTotalSize(totalSize);
            result.setOriginalOutTotalMoney(originalTotalMoney.floatValue());
            result.setExcludeOutMoney(excludeMoney.floatValue());
        }
        if (searchBaseList != null && searchBaseList.size() > 0) {
            log.info("检索的数据入库操作, 共{}条", searchBaseList.size());
            List<AssistPdfSearchBase> searchList = searchBaseList.stream().distinct().collect(Collectors.toList());
            assistPdfSearchBaseService.insertSearchBaseList(searchList);
        } else {
            log.info("未检索到需要入库的数据!");
        }
        log.info("{}数据处理完成！", inOrOut);
    }

    /**
     * @param inOrOut      收入/支出
     * @param excludeMoney 已过滤的金额
     * @param total        总金额
     * @param splitCount   个数
     */
    private List<Integer> getRandomValue(String inOrOut, Integer excludeMoney, int total, int splitCount) {
        double maxValue = (total / splitCount) * 1.5; // 生成金额的最大范围(期待金额平均值的1.5倍)
        Integer max = (int) maxValue;
        Integer min = 20;

        log.info("需要的{}总金额: {}", inOrOut, total);
        log.info("已过滤{}总金额: {}", inOrOut, excludeMoney);
        log.info("除过滤共有{}个数: {}", inOrOut, splitCount);
        log.info("最小金额: {}", min);
        log.info("最大金额: {}", max);
        Integer tempTotal = total;

        List<Integer> moneyList = new ArrayList<Integer>();
        Random random = new Random();
        for (int i = 0; i < splitCount; i++) {
            int num = 0;
            do {
                num = random.nextInt(max);
            } while (num > max || num < min);
            total -= num;
            moneyList.add(num);
        }

        int check_num = 0;
        int check_num_two = 0;

        log.info(Arrays.toString(moneyList.toArray()));

        for (int x : moneyList) {
            check_num = check_num + x;
        }
        int dealMoneyTotal = check_num + excludeMoney;
        log.info("第一次验证总和: {}", dealMoneyTotal);
        if (dealMoneyTotal < tempTotal) {
            log.info("验证总和: {} 小于预期金额，则进行处理...", dealMoneyTotal);
            int stillNeedMoney = (tempTotal - dealMoneyTotal) + (tempTotal / 10); // 仍需的金额数
            int avgAddMoney = stillNeedMoney / moneyList.size(); // 平均每笔收入要增加的金额数
            for (int i = 0; i < moneyList.size(); i++) {
                Integer orginInt = moneyList.get(i);
                Integer newInt = orginInt + avgAddMoney;
                if (newInt > 100 && newInt < 10000) {
                    Integer dealInt = (newInt / 10) * 10;
                    moneyList.set(i, dealInt);
                }
                if (newInt > 10000) {
                    Integer dealInt = (newInt / 100) * 100;
                    moneyList.set(i, dealInt);
                }
            }
        }
        tempTotal = tempTotal + (tempTotal / 10); // 预期值的10%
        if (dealMoneyTotal > tempTotal) {
            log.info("验证总和: {} 大于预期金额的10%，则进行处理...", dealMoneyTotal);
            int stillNeedMoney = (dealMoneyTotal - tempTotal); // 多余的金额数
            int avgDivMoney = stillNeedMoney / moneyList.size(); // 平均每笔支出要减少的金额数
            for (int i = 0; i < moneyList.size(); i++) {
                Integer orginInt = moneyList.get(i);
                if (orginInt > avgDivMoney) {
                    Integer newInt = orginInt - avgDivMoney;
                    if (newInt > 100 && newInt < 10000) {
                        Integer dealInt = (newInt / 10) * 10;
                        moneyList.set(i, dealInt);
                    }
                    if (newInt > 10000) {
                        Integer dealInt = (newInt / 100) * 100;
                        moneyList.set(i, dealInt);
                    }
                }
            }
        }
        log.info("处理金额位数...");
        for (int i = 0; i < moneyList.size(); i++) {
            Integer orginMoney = moneyList.get(i);
            if (orginMoney > 100 && orginMoney < 10000) {
                Integer dealInt = (orginMoney / 10) * 10;
                moneyList.set(i, dealInt);
            }
            if (orginMoney > 10000) {
                Integer dealInt = (orginMoney / 100) * 100;
                moneyList.set(i, dealInt);
            }
        }
        log.info("处理结果：{}", Arrays.toString(moneyList.toArray()));
        Integer maxMoney = Collections.max(moneyList);
        log.info("处理结果最大值：{}", maxMoney);
        for (int x : moneyList) {
            check_num_two = check_num_two + x;
        }
        log.info("再次验证总和: {}", check_num_two + excludeMoney);
        return moneyList;
    }

    private void replaceText(Map<Integer, List<PdfFormData>> needDealMap, List<DealRecord> recordList) {
        if (needDealMap != null && needDealMap.size() > 0) {
            Integer moneyFlag = 0;
            for (Integer pageNum : needDealMap.keySet()) {
                List<PdfFormData> dataList = needDealMap.get(pageNum);
                if (dataList != null && dataList.size() > 0) {
                    for (PdfFormData data : dataList) {
                        data.setAfterText(recordList.get(moneyFlag).getDealMoney() + ".00");
                        moneyFlag++;
                    }
                }
            }
        }
    }

    /**
     * 处理PDF文件流字节，替换map数据
     *
     * @param bytes        文件字节
     * @param outputStream 输出流
     * @param inMap        处理的收入数据
     * @param outMap       处理的支出数据
     * @throws Exception
     */
    private void dealPdfFileBytes(byte[] bytes,
                                  OutputStream outputStream,
                                  Map<Integer, List<PdfFormData>> inMap,
                                  Map<Integer, List<PdfFormData>> outMap,
                                  ResultDomain resultDomain) throws Exception {
        PdfReader reader = new PdfReader(bytes);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        PdfContentByte canvas;
        BigDecimal result = new BigDecimal(0);
        AssistType assistType = resultDomain.getAssistType();

        if (inMap != null && inMap.size() > 0) {
            Float totalInMoney = 0f;
            log.info("修改PDF文件中收入数据内容");
            for (Integer page : inMap.keySet()) {
                canvas = stamper.getOverContent(page);
                List<PdfFormData> dataList = inMap.get(page);
                if (dataList != null) {
                    totalInMoney += updateMoenyText(assistType, dataList, canvas);
                }
            }
            result = new BigDecimal(totalInMoney + resultDomain.getExcludeInMoney());
            log.info("处理后总收入金额为：{}", totalInMoney + resultDomain.getExcludeInMoney());

        }

        if (outMap != null && outMap.size() > 0) {
            Float totalOutMoney = 0f;
            log.info("修改PDF文件中支出数据内容");
            for (Integer page : outMap.keySet()) {
                canvas = stamper.getOverContent(page);
                List<PdfFormData> dataList = outMap.get(page);
                if (dataList != null) {
                    totalOutMoney += updateMoenyText(assistType, dataList, canvas);
                }
            }
            log.info("处理后总支出金额为：{}", totalOutMoney + resultDomain.getExcludeOutMoney());
            result = result.subtract(new BigDecimal(totalOutMoney + resultDomain.getExcludeOutMoney()));
        }
        log.info("处理后收支金额差为：{}", result.intValue());
        log.info("PDF文件内容修改完毕！");
        stamper.close();
        reader.close();
    }

    /**
     * 修改byte流中的数据
     *
     * @param assistType 配置类数据
     * @param dataList   要修改的数据
     * @param canvas     画图工具
     * @throws Exception
     */
    private Float updateMoenyText(AssistType assistType,
                                  List<PdfFormData> dataList,
                                  PdfContentByte canvas) throws Exception {
        Integer fontSize = assistType.getFontSize();
        Float totalMoney = 0f;
        for (PdfFormData data : dataList) {
            BigDecimal top = new BigDecimal(data.getTop());
            BigDecimal defualtHeight = new BigDecimal(assistType.getDefualtHeight());
            float x = new BigDecimal(data.getLeft()).floatValue();
            float y = defualtHeight.subtract(top).floatValue();
            float width = new BigDecimal(data.getWidth()).floatValue();
            String afterText = data.getAfterText();
            // 计算处理后的总金额
            totalMoney += Float.parseFloat(afterText);

            canvas.saveState();
            String rectangleBackColor = assistType.getRectangleBackColor();
            String[] rectColors = rectangleBackColor.split(",");
            canvas.setColorFill(new BaseColor(Integer.parseInt(rectColors[0]), Integer.parseInt(rectColors[1]), Integer.parseInt(rectColors[2])));
            float xOffValue = x + assistType.getOffsetX();
            float yOffValue = y + assistType.getOffsetY();
            canvas.rectangle(xOffValue, yOffValue, assistType.getModifyBoxWidth(), assistType.getModifyBoxHeight());
            canvas.fill();
            canvas.restoreState();
            //开始写入文本
            canvas.beginText();
            // BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            BaseFont bf = BaseFont.createFont(assistType.getFontPath(), BaseFont.CP1252, BaseFont.EMBEDDED);
            Font font = new Font(bf, Font.NORMAL, fontSize);
            float textWidth = font.getBaseFont().getWidthPointKerned(afterText, fontSize);
            float xt = this.getLayoutValueByType(assistType.getLayoutType(), x, width, textWidth);
            String fontColor = assistType.getFontColor();
            String[] fontRgbColors = fontColor.split(",");
            canvas.setRGBColorFill(Integer.parseInt(fontRgbColors[0]), Integer.parseInt(fontRgbColors[1]), Integer.parseInt(fontRgbColors[2]));
            //设置字体和大小
            canvas.setFontAndSize(font.getBaseFont(), fontSize);
            //设置字体的输出位置
            canvas.setTextMatrix(xt, y);
            //要输出的text
            canvas.showText(afterText);
            canvas.endText();
        }
        return totalMoney;
    }

    private float getLayoutValueByType(String type, float x, float width, float textWidth) {
        float value = 0f;
        if (StringUtils.equalsIgnoreCase(type, "left")) {
            // 左对齐
            value = x + 1.6f;
        } else if (StringUtils.equalsIgnoreCase(type, "right")) {
            // 右对齐
            value = (x + width) - textWidth; // 设置文字右对齐X轴标点
        } else {
            // 默认居中
            value = (x + (width / 2)) - (textWidth / 2); // 设置文字居中X轴标点
        }
        return value;
    }

}
